<template>
  <div>
    <el-dialog
      :visible="visible"
      :title="title"
      :operation="operation"
      :width="width"
      append-to-body
      @close="close"
      @closed="closed"
    >
      <el-form
        ref="categoryDataForm"
        :model="categoryDataForm"
        :rules="rules"
        label-width="200px"
        label-position="right"
        label-suffix=":"
      >
        <el-form-item
          :label="$t('categoryLang.categoryLevel')"
          :prop="operation === 1 ? 'categoryLevel' : ''"
        >
          <el-radio-group
            v-if="operation === 1"
            v-model="categoryDataForm.categoryLevel"
            @change="handleSelected"
          >
            <el-radio
              v-for="item in categoryLevelOptionsList"
              :key="item.value"
              :value="item.value"
              :label="item.value"
            >
              {{ $t(item.title) }}
            </el-radio>
          </el-radio-group>
          <div v-else style="margin-left: 5px">
            {{
              $t(
                getTitleByValue(
                  categoryLevelOptionsList,
                  categoryDataForm.categoryLevel
                )
              )
            }}
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('categoryLang.parentId')"
          prop="parentId"
          v-if="
            categoryDataForm.categoryLevel !==
              categoryLevelDict.CLASS_I_CATEGORY.value && operation !== 2
          "
        >
          <el-cascader
            v-model="categoryDataForm.parentId"
            :options="parentIdList"
            :props="{
              expandTrigger: 'hover',
              label: 'categoryName',
              value: 'categoryId',
              children: 'children',
            }"
            style="width: 100%"
            @change="handleChangeCategory"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item
          :label="$t('categoryLang.categoryName')"
          prop="categoryName"
        >
          <el-input
            v-model="categoryDataForm.categoryName"
            :placeholder="$t('pleaseEnter')"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('categoryLang.categoryEnName')"
          prop="categoryEnName"
        >
          <el-input
            v-model="categoryDataForm.categoryEnName"
            :placeholder="$t('pleaseEnter')"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('categoryLang.declaredMinUsdPrice')"
          prop="declaredMinUsdPrice"
          v-if="
            categoryDataForm.categoryLevel ===
            categoryLevelDict.CLASS_III_CATEGORY.value
          "
        >
          <el-input
            v-model="categoryDataForm.declaredMinUsdPrice"
            :placeholder="$t('pleaseEnter')"
            type="number"
            min="0.1"
            clearable
            style="width: 100%"
          >
            <template slot="append">USD</template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('categoryLang.hsCode')"
          prop="hsCode"
          v-if="
            categoryDataForm.categoryLevel ===
            categoryLevelDict.CLASS_III_CATEGORY.value
          "
        >
          <el-input
            v-model="categoryDataForm.hsCode"
            :placeholder="$t('categoryLang.pleaseEnterTenNumbers')"
            clearable
            maxlength="10"
            show-word-limit
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="warning" plain size="small" @click="close">
          {{ $t("cancel") }}
        </el-button>
        <el-button type="primary" size="small" @click="handleSubmit">{{
          $t("submit")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import to from "await-to-js";
import { getDictOptionList, getTitleByValue } from "@/utils/dictUtils";
import { categoryLevelDict } from "@/utils/dictData";
import {
  addCategory,
  modifiedCategory,
  getCategory,
  getCategoryList,
} from "@/api/system/category";
export default {
  name: "CategoryForm",
  props: {
    value: {
      type: Number,
      default: null,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    operation: {
      type: Number,
      default: 0, // 0查看 1新增 2修改
    },
    title: {
      type: String,
      default: null,
    },
    width: {
      type: String,
      default: "750px",
    },
  },
  data() {
    // 最低申报价值
    const validateDeclaredMinUsdPrice = (rule, value, callback) => {
      if (value) {
        if (value < 0.1) {
          callback(new Error(this.$t("categoryLang.MinUsdPrice")));
        } else {
          callback();
        }
      }
    };
    return {
      selectedValue: [],
      parentIdList: [], //上级菜单列表
      getTitleByValue: getTitleByValue,
      categoryLevelDict: categoryLevelDict,
      categoryLevelOptionsList: getDictOptionList(categoryLevelDict), //品类类型
      categoryDataForm: {
        categoryLevel: null,
        parentId: null,
        categoryName: null,
        categoryEnName: null,
        declaredMinUsdPrice: null,
        hsCode: null,
      },
      rules: {
        categoryName: {
          required: true,
          message: this.$t("pleaseEnter"),
          trigger: ["blur"],
        },
        categoryEnName: {
          required: true,
          message: this.$t("pleaseEnter"),
          trigger: ["blur"],
        },
        declaredMinUsdPrice: [
          {
            required: true,
            pattern: /^\d+$|^\d*\.\d+$/g,
            message: this.$t("pleaseEnter"),
            trigger: ["blur", "change"],
          },
          {
            validator: validateDeclaredMinUsdPrice,
            trigger: ["blur", "change"],
          },
        ],
        hsCode: [
          {
            required: true,
            message: this.$t("pleaseEnter"),
            trigger: ["blur", "change"],
          },
          {
            pattern: /^\d{10}$/,
            message: this.$t("pleaseEnter"),
            required: true,
          },
        ],
      },
    };
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal != null && newVal !== undefined && newVal !== oldVal) {
          this.getData();
        }
      },
    },
  },
  created() {
    this.getData();
  },
  methods: {
    async getData() {
      console.log(this.value);
      if (!this.value || this.operation === 1) return;
      const res = await getCategory({
        categoryId: this.value,
      });
      console.log(res);
      if (!res || res.data === null) return;
      this.categoryDataForm = res.data;
    },
    // 级联选择框
    handleChangeCategory(value) {
      console.log(value);
      this.selectedValue = value;
    },
    // 获取上级菜单
    async handleSelected(e) {
      console.log(e);
      const { data } = await getCategoryList({
        categoryLevel: e,
      });
      console.log(data);
      this.parentIdList = data.categoryIdAndNameDTOList;
    },
    // 提交
    async handleSubmit() {
      const [err] = await to(this.$refs.categoryDataForm.validate());
      if (err === null) {
        if (this.operation === 1) {
          // 如果有多级则是三级品类，只选择二级提交，否则只提交一级
          if (this.selectedValue.length === 2) {
            // 选择三级 => 只提交二级
            this.categoryDataForm.parentId = this.selectedValue[1];
          } else if (this.selectedValue.length === 1) {
            // 二级 => 一级
            this.categoryDataForm.parentId = this.selectedValue[0];
          }
          console.log(this.categoryDataForm.parentId);
          const res = await addCategory({
            ...this.categoryDataForm,
            parentId: this.categoryDataForm.parentId,
          });
          if (res.returnCode === 10000) {
            this.$message.success({
              message: this.$t("handleSuccess"),
            });
            this.$emit("close");
            this.$emit("update:operation", 2);
          } else {
            this.$message.error(res.returnMsg);
          }
        } else if (this.operation === 2) {
          // 修改
          const res = await modifiedCategory({
            modifiedUser: 0,
            categoryId: this.value,
            categoryName: this.categoryDataForm.categoryName,
            categoryEnName: this.categoryDataForm.categoryEnName,
            declaredMinUsdPrice: this.categoryDataForm.declaredMinUsdPrice,
            hsCode: this.categoryDataForm.hsCode,
          });
          if (res.returnCode === 10000) {
            this.$message.success({
              message: this.$t("handleSuccess"),
            });
            this.$emit("close");
          } else {
            this.$message.error(res.returnMsg);
          }
        }
      }
    },
    async reset() {
      this.categoryDataForm = {
        categoryLevel: null,
        parentId: null,
        categoryName: null,
        categoryEnName: null,
        declaredMinUsdPrice: null,
        hsCode: null,
      };
      await this.$refs.categoryDataForm.resetFields();
    },
    close() {
      this.$emit("close");
    },
    closed() {
      this.reset();
    },
  },
};
</script>

<style></style>
